package com.libreaccess.reporting.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Logger {
	private final String path = System.getenv("JBOSS_HOME")+File.separator + "server" + File.separator + "default" + File.separator + "log" + File.separator + "reporting.log";
	private String className;
	
	public Logger (Class<?> clazz) {
		className = clazz.getSimpleName();
	}
	/*public void info(String s) {
		saveInformation("info", s);
	}*/

	public void debug(String s) {
		saveInformation("debug", s);
	}
	
	public void warn(String s) {
		saveInformation("warn", s);
	}
	
	public void error(String s) {
		saveInformation("error", s);
	}
	
	private String formatCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
		return format.format(new Date()); 
	}
	
	private void isFileExpired() {
		File f = new File(path);
		if (f.exists()) {
			Calendar calNow = Calendar.getInstance();
			Calendar calFile = Calendar.getInstance();
			calFile.setTimeInMillis(f.lastModified());
			if (calNow.get(Calendar.DATE) != calFile.get(Calendar.DATE)) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				File renFile = new File(path+ "."+format.format(calFile.getTime()));
				f.renameTo(renFile);				
			}
			
		}
	}
	private void saveInformation(String accessLevel, String inf) {
				try {
					isFileExpired(); //verify is file expired
					RandomAccessFile fs = new RandomAccessFile(path, "rw");
					String out="";
					if (fs!= null)
					{
						fs.seek(fs.length());
						StackTraceElement[] tr = Thread.currentThread().getStackTrace();
						if (tr!= null) {
							out = String.format("%s %s [%s:%s] %s\n", formatCurrentTime(), accessLevel.toUpperCase(), className, tr[3].getLineNumber(), inf);
							fs.writeBytes(out );
							System.out.println(out);
						}
						fs.close();
					}
				} catch (FileNotFoundException e) {
					error("FileNotFoundException:"+e.getMessage());
				} catch (IOException e) {
					error("Exception:"+e.getMessage());
				}	


		
	}
	
	

}
